package com.glkj.vipsystem.modules.merchant.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.glkj.vipsystem.common.utils.MyValidator;
import com.glkj.vipsystem.common.utils.PageUtils;
import com.glkj.vipsystem.common.utils.Query;
import com.glkj.vipsystem.common.utils.R;
import com.glkj.vipsystem.common.validator.ValidatorUtils;
import com.glkj.vipsystem.entity.ao.GoodsAO;
import com.glkj.vipsystem.entity.ao.ShopAO;
import com.glkj.vipsystem.entity.form.GoodsPriceForm;
import com.glkj.vipsystem.entity.gen.Depot;
import com.glkj.vipsystem.entity.gen.GoodsPrice;
import com.glkj.vipsystem.entity.gen.Stock;
import com.glkj.vipsystem.modules.sys.controller.AbstractController;
import com.glkj.vipsystem.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商品控制器
 *
 * @author LiMuchan
 */
@RestController
@RequestMapping("/merchant/goods")
public class GoodsController extends AbstractController {

    @Resource
    private IGoodsService goodsService;
    @Resource
    private IDepotService depotService;
    @Resource
    private IStockService stockService;
    @Resource
    private IShopService shopService;
    @Resource
    private IGoodsPriceService goodsPriceService;

    /**
     * 列表
     */
    @RequestMapping(value = "/list")
    @RequiresPermissions(value = {"merchant:goods:all", "cash:order:list"}, logical = Logical.OR)
    public R list(@RequestParam Map<String, Object> params) {
        String companyId = (String) params.get("companyId");
        String shopId = (String) params.get("shopId");
        // 是否为收银
        String cash = (String) params.get("cash");
        if (StringUtils.isBlank(companyId)) {
            return R.ok().put("page", new PageUtils(new Page<>()));
        }
        String goodsCatId = (String) params.get("goodsCatId");
        String goodsName = (String) params.get("goodsName");
        Wrapper<GoodsAO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("id desc");
        wrapper.setSqlSelect("*,(select cat_name from t_goods_cat where id = t_goods.cat_id) as cat_name");
        wrapper.eq("company_id", Integer.valueOf(companyId));

        if (StringUtils.isNotBlank(goodsCatId)) {
            wrapper.where("cat_id in (select id from t_goods_cat where FIND_IN_SET('" + goodsCatId + "',`all_id`))");
        }
        if (StringUtils.isNotBlank(goodsName)) {
            wrapper.like("goods_name", goodsName);
        }
        Page<GoodsAO> page = goodsService.selectPage(
                new Query<GoodsAO>(params).getPage(), wrapper
        );
        List<GoodsAO> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records) && StringUtils.isNotBlank(shopId)) {
            // 库存数量
            Depot depot = depotService.selectOne(
                    new EntityWrapper<Depot>()
                            .eq("shop_id", shopId)
                            .last("limit 1")
            );
            if (depot != null) {
                Integer depotId = depot.getId();
                for (GoodsAO record : records) {
                    Stock stock = stockService.selectOne(
                            new EntityWrapper<Stock>()
                                    .eq("shop_id", shopId)
                                    .eq("depot_id", depotId)
                                    .eq("goods_id", record.getId())
                    );
                    if (stock != null) {
                        record.setNum(stock.getNum());
                    }
                }
            }
            // 若是收银 商品价格为店铺价格
            if (StringUtils.isNotBlank(cash)) {
                List<GoodsPrice> priceList = goodsPriceService.selectList(
                        new EntityWrapper<GoodsPrice>()
                                .eq("shop_id", shopId)
                );
                if (!CollectionUtils.isEmpty(priceList)) {
                    for (GoodsAO goodsAO : records) {
                        for (int i = 0; i < priceList.size(); i++) {
                            GoodsPrice price = priceList.get(i);
                            if (price.getGoodsId().compareTo(goodsAO.getId()) == 0) {
                                goodsAO.setGoodsPrice(price.getGoodsPrice());
                                goodsAO.setGoodsDiscount(price.getGoodsDiscount());
                                priceList.remove(i);
                                break;
                            }
                        }
                    }
                }
            }
        }
        return R.ok().put("page", new PageUtils(page));
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{id}")
    @RequiresPermissions({"merchant:goods:all"})
    public R detail(@PathVariable("id") Integer id) {
        return R.ok().put("item", goodsService.selectById(id));
    }

    /**
     * 保存新增
     */
    @RequestMapping(value = "/save")
    @RequiresPermissions({"merchant:goods:all"})
    public R save(@RequestBody GoodsAO goods) {
        ValidatorUtils.validateEntity(goods);
        BigDecimal goodsPrice = goods.getGoodsPrice();
        if (new BigDecimal("0").compareTo(goodsPrice) >= 0) {
            return R.error("商品价格必须大于0");
        }
        String plainString = goodsPrice.toPlainString();
        if (!MyValidator.isMoney(plainString)) {
            return R.error("请输入正确的商品价格");
        }
        try {
            goodsService.save(goods);
        } catch (DuplicateKeyException e) {
            return R.error("商品名称重复");
        }
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @RequiresPermissions({"merchant:goods:all"})
    public R update(@RequestBody GoodsAO goods) {
        ValidatorUtils.validateEntity(goods);
        goods.setCompanyId(null); // 不允许修改所属公司
        try {
            goodsService.updateById(goods);
        } catch (DuplicateKeyException e) {
            return R.error("商品名称重复");
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @RequiresPermissions({"merchant:goods:all"})
    public R delete(@RequestBody Integer[] ids) {
        if (ids != null && ids.length > 0) {
            goodsService.deleteBatch(Arrays.asList(ids));
        }
        return R.ok();
    }

    /**
     * 获取商品店铺价格列表
     */
    @GetMapping(value = "shop-price/{goodsId}")
    @RequiresPermissions({"merchant:goods:all"})
    public R shopPrice(@PathVariable("goodsId") Integer goodsId) {
        GoodsAO goodsAO = goodsService.selectById(goodsId);
        if (goodsAO == null) return R.error("商品不存在");

        // 查询商品店铺进行封装价格
        Wrapper<ShopAO> wrapper = new EntityWrapper<>();
        // 角色权限校验
        wrapper.eq("company_id", goodsAO.getCompanyId());
        if (isEmployeeRole()) {
            // 员工 只查看当前店铺
            wrapper.where("id = (select shop_id from t_employee where username = '" + getUser().getUsername() + "')");
        }
        List<ShopAO> shops = shopService.selectList(wrapper);
        List<GoodsPrice> goodsPrices = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shops)) {
            // 获取已设置的店铺价格
            List<GoodsPrice> priceList = goodsPriceService.selectList(
                    new EntityWrapper<GoodsPrice>()
                            .eq("goods_id", goodsId)
            );
            for (ShopAO shop : shops) {
                GoodsPrice goodsPrice = new GoodsPrice();
                goodsPrice.setGoodsId(goodsId)
                        .setGoodsPrice(goodsAO.getGoodsPrice())
                        .setGoodsDiscount(goodsAO.getGoodsDiscount())
                        .setShopId(shop.getId())
                        .setShopName(shop.getShopName());
                // 查看是否已设置了价格
                if (!CollectionUtils.isEmpty(priceList)) {
                    for (int i = 0; i < priceList.size(); i++) {
                        GoodsPrice price = priceList.get(i);
                        if (price.getShopId().compareTo(shop.getId()) == 0) {
                            goodsPrice.setGoodsPrice(price.getGoodsPrice());
                            goodsPrice.setId(price.getId());
                            goodsPrice.setGoodsDiscount(price.getGoodsDiscount());
                            priceList.remove(i);
                            break;
                        }
                    }
                }
                goodsPrices.add(goodsPrice);
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("goods", goodsAO);
        data.put("priceList", goodsPrices);
        return R.ok().put("data", data);
    }

    /**
     * 保存商品店铺价格
     */
    @PostMapping(value = "save-shop-price")
    @RequiresPermissions({"merchant:goods:all"})
    public R saveShopPrice(@RequestBody GoodsPriceForm form) {
        if (form == null) return R.error("数据错误");

        List<GoodsPrice> priceList = form.getPriceList();
        if (CollectionUtils.isEmpty(priceList)) return R.error("请填写店铺价格");

        // 数据校验
        for (GoodsPrice goodsPrice : priceList) {
            if (goodsPrice.getShopId() == null
                    || goodsPrice.getGoodsId() == null
                    || goodsPrice.getGoodsPrice() == null) {
                return R.error("数据错误");
            }
            goodsPrice.setGoodsPrice(goodsPrice.getGoodsPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        goodsPriceService.insertOrUpdateBatch(priceList);
        return R.ok();
    }

}
